package main

import (
	"flag"
	"log"
	"os"
	"path/filepath"
	"sync"
)

type args struct {
	path, file string
}

var (
	que chan args
	wg  *sync.WaitGroup
)

func main() {
	path := flag.String("p", "", "remove file dir path")
	file := flag.String("f", ".DS_Store", "remove file name")
	flag.Parse()
	if *path == "" {
		log.Println("must use -p to setup dir path")
		return
	}
	fi, err := os.Stat(*path)
	if err != nil {
		log.Println(err)
		return
	}
	if !fi.IsDir() {
		log.Println("-p parameter must be a dir")
		return
	}
	que = make(chan args, 1024)
	wg = new(sync.WaitGroup)
	start()
	submit(*path, *file)
	wg.Wait()
	close(que)
}

func start() {
	for i := 0; i < 10; i++ {
		go func() {
			for a := range que {
				deal(a)
			}
		}()
	}
}

func submit(path, file string) {
	wg.Add(1)
	que <- args{path: path, file: file}
}

func deal(a args) {
	defer wg.Done()
	dirs, err := os.ReadDir(a.path)
	if err != nil {
		log.Println("os.ReadDir err:", err)
		return
	}
	for _, dir := range dirs {
		if dir.IsDir() {
			if dir.Name() == ".git" {
				continue
			}
			submit(filepath.Join(a.path, dir.Name()), a.file)
			continue
		}
		info, err := dir.Info()
		if err != nil {
			log.Println("dir.Info err:", err)
			continue
		}
		if a.file == info.Name() {
			if err = os.Remove(filepath.Join(a.path, info.Name())); err != nil {
				log.Println("remove", info.Name(), "failed err:", err)
			}
		}
	}
}
